//
//  HMEntryReport.swift
//  HealthMonitoring
//
//  Created by YTYanK on 2018/10/8.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import SwiftyJSON

class HMEntryReport: HMViewController {

    var erSelectedPhotos = NSMutableArray()
    var erSelectedAssets = NSMutableArray()
    var erIsSelectOriginalPhoto: Bool = false
    var erCollectionView: UICollectionView?
    var maxCountNum: Int = 0
    ///
    var erLayout: UICollectionViewFlowLayout?
    var erMargin: CGFloat = 0.0
    var erItemWH: CGFloat = 0.0
    
    
    ///  类型 1 健康报告, 2 专项报告  。默认 1
    var erType: Int = 1
    
    /// 专项的父级ID
    var pId = ""
    var subIds = Array<Int>()
    
    /// 传入的数据
    var erJsonData = JSON()
    /// urls
    var photoUrls = NSMutableArray()
    /// urls 图片集
    var urlImges = NSMutableArray()
    /// 是否编辑状态 , 默认 false,
    var isEditState: Bool = false
    /// 选择的
    var selectIndexPath: IndexPath?
    
    //MARK: - 常量
    let erTitleLabel = UILabel()
    let erTitle = UITextField()
    let erDateLabel = UILabel()
    let erDate = UIButton()
    let erRemarksLabel = UILabel()
    let erRemarks = UITextField()
    let addBtn = UIButton()
    
    
    override func setupView() {
        self.title = "报告录入"
        view.backgroundColor = UIColor.white
        
        maxCountNum = 9 // 设置最大可选数量
        erCollectionView = configCollectionView()
        view.addSubview(erCollectionView!)
        
        
       view.addSubview(erTitleLabel)
       view.addSubview(erTitle)
       view.addSubview(erDateLabel)
       view.addSubview(erDate)
       view.addSubview(erRemarksLabel)
       view.addSubview(erRemarks)
        view.addSubview(addBtn)
        
        erTitleLabel.frame = CGRect.init(x: 8, y: 130.0 + 10.0, width: 50, height: 44)
        erTitleLabel.text = "名称:"
        erTitleLabel.backgroundColor = .red
        
        
        erTitle.topAlign(view: erTitleLabel, predicate: "0")
        erTitle.leadingHorizontally(view: erTitleLabel, predicate: "10")
        erTitle.placeholder = "内容"
        erTitle.trailingAlign(view: view)
        erTitle.heightConstrain(predicate: "44")
//        erTitle.widthConstrain(predicate: "100")
        erTitle.backgroundColor = .blue
        erTitle.layer.borderWidth = 1
        erTitle.layer.borderColor = configure.shareConfigure.HMColor3.cgColor
        erTitle.layer.cornerRadius = 8
        
        
        erDateLabel.topVertically(view: erTitleLabel, predicate: "10")
        erDateLabel.leadingAlign(view: view)
        erDateLabel.text = "日期:"
        erDateLabel.heightConstrain(predicate: "44")
        erDateLabel.widthConstrain(predicate: "50")

        
        erDate.setTitle("2018-12-11", for: UIControlState.normal)
        erDate.setTitleColor(UIColor.black, for: .normal)
        erDate.topAlign(view: erDateLabel, predicate: "0")
        erDate.leadingHorizontally(view: erDateLabel, predicate: "10")
        erDate.trailingAlign(view: view)
        erDate.heightConstrain(predicate: "44")
        erDate.layer.borderWidth = 1
        erDate.layer.borderColor = configure.shareConfigure.HMColor3.cgColor
        erDate.layer.cornerRadius = 8

        
        
        erRemarksLabel.topVertically(view: erDateLabel, predicate: "10")
        erRemarksLabel.leadingAlign(view: view)
        erRemarksLabel.text = "备注:"
        erRemarksLabel.heightConstrain(predicate: "44")
        erRemarksLabel.widthConstrain(predicate: "50")
        
        erRemarks.placeholder = "输入备注内容"
        erRemarks.leadingHorizontally(view: erRemarksLabel, predicate: "10")
        erRemarks.trailingAlign(view: view)
        erRemarks.topAlign(view: erRemarksLabel, predicate: "0")
        erRemarks.heightConstrain(predicate: "44")
        erRemarks.layer.borderWidth = 1
        erRemarks.layer.borderColor = configure.shareConfigure.HMColor3.cgColor
        erRemarks.layer.cornerRadius = 8
        
        
        addBtn.topVertically(view: erRemarksLabel, predicate: "20")
        addBtn.heightConstrain(predicate: "44")
        addBtn.leadingAlign(view: view, predicate: "20")
        addBtn.trailingAlign(view: view, predicate: "-20")
//        addBtn.layer.borderColor = configu
        addBtn.layer.cornerRadius = 8
        addBtn.setTitle("添加报告", for: .normal)
        addBtn.setTitleColor(UIColor.white, for: .normal)
        addBtn.backgroundColor = configure.shareConfigure.HMColor1
        addBtn.addTarget(self, action: #selector(addClick), for: UIControlEvents.touchUpInside)
        
        
        if isEditState {
            erTitle.text =  self.erJsonData["title"].stringValue
              let dateStr: String = erJsonData["createDate"].stringValue
            erDate.setTitle(String(dateStr.prefix(10)), for: .normal)
            erRemarks.text = erJsonData["mark"].stringValue
            addBtn.setTitle("保存编辑", for: .normal)
        }
        
        
    }
    
    
    
    
    
    private func configCollectionView() -> UICollectionView{
        erLayout = UICollectionViewFlowLayout()
        let coll = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: erLayout!)
        coll.backgroundColor = UIColor.green  //clear
        coll.isScrollEnabled = false
        coll.alwaysBounceVertical = true
        coll.contentInset = UIEdgeInsetsMake(4, 4, 4, 4)
        coll.register(TZTestCell.classForCoder(), forCellWithReuseIdentifier: "TZTestCell")
        coll.dataSource = self
        coll.delegate = self
        
        erMargin =  4.0
        erItemWH = (configure.shareConfigure.screenWidth - 16.0 - 2.0 * erMargin - 4.0) / 3 - erMargin
        erLayout?.itemSize = CGSize.init(width: erItemWH, height: erItemWH)
        erLayout?.minimumInteritemSpacing = erMargin
        erLayout?.minimumLineSpacing = erMargin
        coll.setCollectionViewLayout(erLayout!, animated: true)
        let collectionViewY :  CGFloat = 0
        coll.frame =  CGRect.init(x: 0, y: collectionViewY, width: configure.shareConfigure.screenWidth, height: 138)
        
        return coll
    }
    
    @objc func addClick(sender: UIButton) {
        
        if isEditState {
          NetRequestTool.shareInstance.met = .post
            var dic = [
                "id": self.erJsonData["id"].stringValue
                ,"pId": self.erJsonData["pId"].stringValue
//                ,"subIds": self.erJsonData["subIds"].arrayObject!
                ,"type": self.erType
                ,"title": self.erTitle.text!
                ,"mark": self.erRemarks.text!
                ,"imageUrls": self.photoUrls
                ] as [String : Any]
            
            if self.erJsonData["subIds"] != nil {
                dic["subIds"] = self.erJsonData["subIds"].arrayObject
            }
            
            NetRequestTool.requestForJSON(url: "user/exam-report", parameters: dic, success: { (json) in
                self.navigationController?.popViewController(animated: true)
                self.showToastImage(message: "编辑成功")
            }, fail: { (code, msg) in
                self.showToastImage(message: "编辑失败")
            }) {}
        }else {
            
            
//            HMPhotoView.requestImages(photos: (self.erSelectedPhotos as! [UIImage]))
            HMPhotoView.requestImages(photos: (self.erSelectedPhotos as! [UIImage])) {
                
                NetRequestTool.shareInstance.met = .post
                var dic  = [
                    "type": self.erType,
                    "title": self.erTitle.text!,
                    "mark":  self.erRemarks.text!,
                    "imageUrls": HMPhotoView.share.urls] as [String : Any]
                if self.erType == 2 {
                    dic = [
                        "pId": self.pId,
                        "subIds": self.subIds,
                        "type": self.erType,
                        "title": self.erTitle.text!,
                        "mark":  self.erRemarks.text!,
                        "imageUrls": HMPhotoView.share.urls] as [String : Any]
                }
                
                NetRequestTool.requestForJSON(url: "user/exam-report", parameters: dic, success: { (json) in
                    print("HMEntryRe------>>>\(json)")
                    
                    // 成功清空路径
                    HMPhotoView.share.urls.removeAll()
                    self.navigationController?.popViewController(animated: true)
                }, fail: { (code, msg) in
                    print("HMEntryRe-----?>>>\(code)->",msg)
                }) { }
                
                
            }
            
                
        
        }
    }
}


extension HMEntryReport: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        
        var count =  0
        if isEditState  {
            if erSelectedPhotos.count >= maxCountNum {
                return photoUrls.count
            }
            
           count = photoUrls.count + 1
        }else {
            if erSelectedPhotos.count >= maxCountNum {
                return erSelectedPhotos.count
            }
           count = erSelectedPhotos.count + 1
        }

        return count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TZTestCell", for: indexPath) as! TZTestCell
        cell.videoImageView.isHidden = true
        
        
         if isEditState == false  {
        
            if indexPath.item == erSelectedPhotos.count {
                cell.imageView.image = UIImage.init(named: "yszs.png")
                //            cell.imageView.isUserInteractionEnabled = true
                cell.deleteBtn.isHidden = true
                cell.gifLable.isHidden = true //显示动态
            }else {
               
                cell.imageView.image = erSelectedPhotos[indexPath.item] as? UIImage
                cell.asset = erSelectedAssets[indexPath.item]
                cell.gifLable.isHidden = true
                cell.deleteBtn.isHidden = false
            }
            
         }else {
            if indexPath.item == photoUrls.count {
                cell.imageView.image = UIImage.init(named: "yszs.png")
                //            cell.imageView.isUserInteractionEnabled = true
                cell.deleteBtn.isHidden = true
                cell.gifLable.isHidden = true //显示动态
                
            }else {
                let imgUrl = configure.shareConfigure.IP_diagonal + (photoUrls[indexPath.item] as! String)
                cell.imageView.img(url: imgUrl)
                cell.gifLable.isHidden = true
                cell.deleteBtn.isHidden = false
                
                self.urlImges.add(cell.imageView.image!)
            }
         }
            
            cell.deleteBtn.tag = indexPath.item
            cell.deleteBtn.addTarget(self, action: #selector(deleteBtnClick), for: UIControlEvents.touchUpInside)
        
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if isEditState {
            
            if indexPath.item == self.urlImges.count {
                
            }else {
                print("预览部分照片")
                // Url 图片预览有问题
                let imagePicker = HMPhotoView.share.showImagePickerController(self, photos: (self.urlImges as! [UIImage]), assets: (NSMutableArray() as! [Any]), index: indexPath.item, max: maxCountNum)
                
//                imagePicker.didFinishPickingPhotosHandle = {
//                    (photos: [UIImage]!, assets: [Any]!, isSelectOriginalPhoto: Bool) -> () in
//                    //回调
//                    
//                    //                    self.erSelectedPhotos = NSMutableArray.init(array: photos)
//                    //                    self.erSelectedAssets = NSMutableArray.init(array: assets)
//                    //                    self.erIsSelectOriginalPhoto = isSelectOriginalPhoto
//                    //                    self.erCollectionView?.reloadData()
//                    //                    self.erCollectionView?.contentSize = CGSize.init(width: 0, height: ((CGFloat(self.erSelectedPhotos.count) + 2.0) / 3.0) * (self.erMargin + self.erItemWH))
//                }
            }
   
            
        }else {
            
            if indexPath.item == self.erSelectedPhotos.count {
                print("去相册选择")
                
                HMPhotoView.share.pv_isSelectOriginalPhoto = true
                let pushImagePicker =  HMPhotoView.share.pushImagePickerController(self, max: maxCountNum, column: 3, selectedAssets: self.erSelectedAssets)
                pushImagePicker.didFinishPickingPhotosHandle = {
                    (photos: [UIImage]!, assets: [Any]!, isSelectOriginalPhoto: Bool) -> () in
                    
                    
                    self.erSelectedPhotos = NSMutableArray.init(array: photos)
                    self.erSelectedAssets = NSMutableArray.init(array: assets)
                    self.erIsSelectOriginalPhoto = isSelectOriginalPhoto
                    
                    self.erCollectionView?.frame.size.height =  CGFloat((self.erSelectedPhotos.count / 3) * 138) + 120.0
                    self.erTitleLabel.frame.origin.y = (self.erCollectionView?.wHeight)! + 10.0
                    self.erCollectionView?.reloadData()
                    
                }
                /// 你可以通过block或者代理，来得到用户选择的照片.
                
            }else { // preview photos or video / 预览照片或者视频
                print("预览部分照片")
                let imagePicker = HMPhotoView.share.showImagePickerController(self, photos: (self.erSelectedPhotos as! [UIImage]), assets: (self.erSelectedAssets as! [Any]), index: indexPath.item, max: maxCountNum)
                imagePicker.didFinishPickingPhotosHandle = {
                    (photos: [UIImage]!, assets: [Any]!, isSelectOriginalPhoto: Bool) -> () in
                    //回调
                    //                    HMPhoto.requestImages(photos: photos)
                    self.erSelectedPhotos = NSMutableArray.init(array: photos)
                    self.erSelectedAssets = NSMutableArray.init(array: assets)
                    self.erIsSelectOriginalPhoto = isSelectOriginalPhoto
                    self.erCollectionView?.reloadData()
                    self.erCollectionView?.contentSize = CGSize.init(width: 0, height: ((CGFloat(self.erSelectedPhotos.count) + 2.0) / 3.0) * (self.erMargin + self.erItemWH))
                }
                
            }

        }
        
        
        
    }
    
    /**
     * 删除按钮事件 -有问题
     */
    @objc func deleteBtnClick(sender: UIButton) {
        
        if isEditState {
            self.photoUrls.removeObject(at: sender.tag)
            
            self.erCollectionView?.performBatchUpdates({
                let indexP: IndexPath = NSIndexPath.init(item: sender.tag, section: 0) as IndexPath
                self.erCollectionView?.deleteItems(at: [indexP])
            }, completion: { (isfinished) in
                self.erCollectionView?.reloadData()
            })
            
        }else {
            
            if  self.collectionView(self.erCollectionView!, numberOfItemsInSection: 0) <= erSelectedPhotos.count {
                self.erSelectedPhotos.remove(sender.tag)
                self.erSelectedAssets.remove(sender.tag)
                self.erCollectionView?.reloadData()
                return
                
            }
            
            self.erSelectedPhotos.remove(self.erSelectedPhotos[sender.tag])  //removeObject(at: sender.tag)   //remove(s)
            self.erSelectedAssets.removeObject(at: sender.tag)
            
            self.erCollectionView?.performBatchUpdates({
                let indexP: IndexPath = NSIndexPath.init(item: sender.tag, section: 0) as IndexPath
                self.erCollectionView?.deleteItems(at: [indexP])
            }, completion: { (isfinished) in
                self.erCollectionView?.reloadData()
            })
            
        }
     
        
    }
}
